
package com.sausageking.auth;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.googlecode.objectify.Key;
import com.sausageking.server.dao.GenericDao;
import com.sausageking.shared.Deal;

@SuppressWarnings("serial")
public class AddDealServlet extends HttpServlet {

  private static final Logger log = Logger.getLogger(AddDealServlet.class
      .getName());

  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    String merchantName = req.getParameter("merchantName");
    String offerDescription = req.getParameter("offerDescription");
    String address = req.getParameter("address");
    String offerType = req.getParameter("offerType");

    // Get the image representation
    ServletFileUpload upload = new ServletFileUpload();
    try {
      FileItemIterator iter = upload.getItemIterator(req);
      FileItemStream imageItem = iter.next();
      InputStream imgStream = imageItem.openStream();
      // construct our entity objects
      Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
      Deal deal = new Deal().setMerchantName(merchantName)
          .setOfferDescription(offerDescription).setAddress(address)
          .setOfferType(offerType).setImage(imageBlob.getBytes());

      // persist image
      GenericDao<Deal> dao = new GenericDao<Deal>(Deal.class);
      Key<Deal> key = dao.put(deal);

      // respond to query
      resp.setContentType("text/plain");
      resp.getOutputStream().write("OK!".getBytes());
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
